<template>
  <Teleport to="body">
    <transition name="el-zoom-in-left">
      <div
        ref="contextMenu"
        v-if="showMenu"
        class="context-menu absolute z-99 py-5px rounded-4px"
        :style="{ left: x + 'px', top: y + 'px' }"
      >
        <!-- 添加菜单的点击事件 -->
        <div
          @click="handleClick(item)"
          class="menu-item"
          v-for="item in props.menu"
          :key="item.label"
        >
          <AppIcon
            :icon="item.icon"
            class="mr-8px"
          />
          {{ item.label }}
        </div>
      </div>
    </Transition>
  </Teleport>
</template>
<script setup>
import { onClickOutside } from '@vueuse/core'

const contextMenu = ref(null)
onClickOutside(contextMenu, event => {
  showMenu.value = false
})

const props = defineProps({
  menu: {
    type: Array,
    default: () => [],
  },
  x: {
    type: Number,
    default: 0,
  },
  y: {
    type: Number,
    default: 0,
  },
})
const showMenu = defineModel({
  type: Boolean,
  default: false,
})
const emit = defineEmits(['select'])
// 菜单的点击事件
function handleClick (item) {
  // 选中菜单后关闭菜单
  showMenu.value = false
  // 并返回选中的菜单
  emit('select', item)
}
</script>
<style lang="scss" scoped>
.context-menu {
  background: var(--el-bg-color-overlay);
  border: 1px solid var(--el-border-color-light);
  box-shadow: 0px 0px 12px rgba(0, 0, 0, .12);
  .menu-item{
    display: flex;
    align-items: center;
    white-space: nowrap;
    list-style: none;
    line-height: 22px;
    padding: 5px 16px;
    margin: 0;
    font-size: var(--el-font-size-base);
    color: var(--el-text-color-regular);
    cursor: pointer;
    outline: none;
    &:hover {
      background-color: var(--el-menu-hover-bg-color);
      color: var(--el-menu-hover-text-color);
    }
  }
}
</style>
